package com.shen.server;

import com.shen.user.User;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Author:shen
 * CreateDate:2020/6/9.
 * Function:
 */
public class TCPClient {
    public static void main(String[] args) {
        Socket socket=null;
        InputStream inputStream =null;
        OutputStream outputStream=null;
        BufferedReader bufferedReader=null;
        ObjectOutput objectOutput=null;
        try {
         socket=new Socket(InetAddress.getByName("127.0.0.1"),3333);

            //录入对象
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            User user=new User();
            System.out.println("请输入用户名：");
            String name = bufferedReader.readLine();
            user.setName(name);
            System.out.println("请输入密码：");
            String password=bufferedReader.readLine();
            user.setPassword(password);

            //发送对象
            outputStream = socket.getOutputStream();
            objectOutput=new ObjectOutputStream(outputStream);
            objectOutput.writeObject(user);
            socket.shutdownOutput();

            //接收服务器传输过来的信息
             inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len=inputStream.read(bytes))!=-1){
                inputStream.read(bytes,0,bytes.length);
            }
            System.out.println(new String(bytes,0,bytes.length));

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(objectOutput!=null){
                try {
                    objectOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
